﻿using NFine.Application.Biz;
using NFine.Application.ProductManage;
using NFine.Application.SystemManage;
using NFine.Code;
using NFine.Domain.Entity.Biz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace NFine.Web.Areas.ProductManage.Controllers
{
    public class OrderController : ControllerBase
    {
        private ProductApp productApp = new ProductApp();
        private UserOrderApp orderApp = new UserOrderApp();
        private UserDetailApp userDetailApp = new UserDetailApp();
        private UserApp userApp = new UserApp();
        
        [HttpGet]
        public override ActionResult Form()
        {
            var u = OperatorProvider.Provider.GetCurrent();
            if (u.IsOrder)
            {
                var user = userApp.GetForm(u.UserId);
                u.IsOrder = user.F_DutyId != "1";
            }
            ViewData["FirstOrder"] = u.IsOrder;
            ViewData["OrderMoney"] = Convert.ToInt32(Configs.GetValue("PayMoney"));
            ViewData["UserName"] = u.UserName;
            ViewData["phone"] = u.phone;
            //获取中转中心
            ViewData["TransferCenterList"] = userApp.GetAllTransferCenter();

            if (!u.IsOrder)
            {
                var order = orderApp.GetLastOrderByUserID(u.UserId);
                ViewData["tid"] = order != null ? order.F_TransferCenterId : "";
            }
            else
            {
                ViewData["tid"] = "";
            }
            //获取商品
            var list = productApp.GetList();
            return View(list);
        }
        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult SubmitForm(UserOrderEntity orderEntity, string jsonData)
        {
            
            jsonData = Server.UrlDecode(jsonData);
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            List<OrderItemEntity> list_OrderItems = serializer.Deserialize<List<OrderItemEntity>>(jsonData);

            var u = OperatorProvider.Provider.GetCurrent();

            orderEntity.F_TotalMoney = list_OrderItems.Sum(a => a.F_TotalPrice);

            if (u.IsOrder)
            {
                var user = userApp.GetForm(u.UserId);
                u.IsOrder = user.F_DutyId != "1";
            }

            //if (u.IsOrder &&
            //orderEntity.F_TotalMoney < Convert.ToInt32(Configs.GetValue("PayMoney")))
            //{
            //    return Error("首次订单金额不足！");
            //}
            orderEntity.F_ProductPrice = orderEntity.F_TotalMoney;
            orderEntity.F_ProductNumber = 0;//表示此为首次订单

            orderEntity.F_Id = Common.GuId();
            orderEntity.F_OrderCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            orderEntity.F_MemberId = OperatorProvider.Provider.GetCurrent().UserId;
            orderEntity.F_OrderTime = DateTime.Now;
            orderEntity.F_OrderStatus = 0;
            orderEntity.F_SendGoodsStatus = 0;
            foreach (var item in list_OrderItems)
            {
                item.F_Id = Common.GuId();
                item.F_OrderCode = orderEntity.F_OrderCode;
            }

            //订单操作 跟踪
            OrderActionEntity actionEntity = new OrderActionEntity();
            //actionEntity.F_Id = Common.GuId();
            //actionEntity.F_OrderCode = orderEntity.F_OrderCode;
            //actionEntity.F_UserId = orderEntity.F_MemberId;
            //actionEntity.F_Username = OperatorProvider.Provider.GetCurrent().UserName;
            //actionEntity.F_ActionCode = "创建订单";
            //actionEntity.F_ActionDate = orderEntity.F_OrderTime;
            //actionEntity.F_Remark = "创建订单";

            var result = orderApp.SubmitOrder(orderEntity, list_OrderItems, actionEntity);


            if (result > 0)
            {
                return Success("订单提交成功！");
            }
            else
                return Error("订单提交失败！");
        }

        /// <summary>
        /// 获取订单列表---代理商
        /// </summary>
        /// <param name="pagination"></param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetGridJson(Pagination pagination, int Type, string OrderCode, string Consignee,
            string OrderTimeStart, string OrderTimeEnd)
        {
            var u = OperatorProvider.Provider.GetCurrent();
            var mid = string.Empty;
            if (u != null)
                mid = u.UserId;
            var data = new
            {
                rows =
                orderApp.GetListForOrder(pagination, Type, OrderCode, Consignee, OrderTimeStart, OrderTimeEnd,mid),
                total = pagination.total,
                page = pagination.page,
                records = pagination.records
            };
            return Content(data.ToJson());
        }

        /// <summary>
        /// 获取订单列表---系统用户
        /// </summary>
        /// <param name="pagination"></param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetGridJson_admin(Pagination pagination, int Type, string OrderCode, string Consignee,
            string OrderTimeStart, string OrderTimeEnd)
        {
            var data = new
            {
                rows =
                orderApp.GetListForOrder(pagination, Type, OrderCode, Consignee, OrderTimeStart, OrderTimeEnd),
                total = pagination.total,
                page = pagination.page,
                records = pagination.records
            };
            return Content(data.ToJson());
        }

        /// <summary>
        /// 查看订单
        /// </summary>
        /// <param name="id">订单id</param>
        /// <returns></returns>
        /*[HttpPost]
        [HandlerAjaxOnly]*/
        public override ActionResult Details()
        {
            //根据订单号查询订单基本信息
            var model = orderApp.GetForm(Request["Id"]);

            model.OrderItems = orderApp.GetOrderItmes(model.F_OrderCode);

            return View(model);
        }


        public ActionResult SetFH()
        {
            //根据订单号查询订单基本信息
            var model = orderApp.GetForm(Request["Id"]);

            model.OrderItems = orderApp.GetOrderItmes(model.F_OrderCode);

            return View(model);
        }

        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult SendOrder(string orderId)
        {
            if (orderApp.UpdateOrderStatus(orderId)>0)
            {
                return Success("订单处理成功！");
            }
            else
            {
                return Error("订单处理失败！");
            }
        }

        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult ZFOrder(string orderId)
        {
            ///作废订单
            if (orderApp.ZFOrder(orderId,-2) > 0)
            {
                return Success("订单已作废！");
            }
            else
            {
                return Error("订单处理失败！");
            }
        }

        /// <summary>
        /// 设置发货
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult FHOrder(string orderId, string kdcode ,string kdnum)
        {
            ///设置发货
            if (orderApp.FHOrder(orderId, kdcode,kdnum) > 0)
            {
                return Success("订单已发货！");
            }
            else
            {
                return Error("订单处理失败！");
            }
        }
        /// <summary>
        /// 设置完成
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult OverOrder(string orderId)
        {
            ///设置发货
            if (orderApp.ZFOrder(orderId, 3) > 0)
            {
                return Success("订单已完成！");
            }
            else
            {
                return Error("订单处理失败！");
            }
        }

        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult QXOrder(string orderId)
        {
            ///取消订单
            if (orderApp.ZFOrder(orderId,-1) > 0)
            {
                return Success("订单已取消！");
            }
            else
            {
                return Error("订单处理失败！");
            }
        }



        public ActionResult Update(string orderId)
        {
            return View(orderApp.GetForm(orderId));
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult UpdateMoney(string orderId, decimal moeny1, decimal moeny2)
        {
            var user = OperatorProvider.Provider.GetCurrent();
            if (user != null&&user.IsSys)
            {
                var order = orderApp.GetForm(orderId);
                if (order != null)
                {
                    order.F_ProductPrice = moeny2;
                    order.F_TotalMoney = moeny1;
                    if (orderApp.UpdateEntity(order))
                    {
                        return Success("订单价格修改成功！");
                    }
                    else
                    {
                        return Error("订单价格修改失败！");
                    }
                }
                else
                {
                    return Error("订单ID不存在！");
                }
            }
            else
            {
                return Error("用户不存具备操作权限！");
            }
        }

        [HttpGet]
        public ActionResult OrderList()
        {
            return View();
        }
    }
}
